//
//  QrCodeViewController.m
//  EcmDoctor
//
//  Created by Mac on 16/2/28.
//  Copyright © 2016年 张进. All rights reserved.
//

#import "QrCodeViewController.h"
#import<AVFoundation/AVFoundation.h>
#import "Qrcodem.h"
#import "AppUtils.h"
@interface QrCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate>
{
    int num;
    BOOL upOrdown;
    NSTimer * timer;
    AVCaptureSession * _AVSession;//调用闪光灯的时候创建的类
 
    UIView *_flshView;

}
@property (strong,nonatomic)AVCaptureDevice * device;

@property (strong,nonatomic)AVCaptureDeviceInput * input;

@property (strong,nonatomic)AVCaptureMetadataOutput * output;

@property (strong,nonatomic)AVCaptureSession * session;

@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;
@property (nonatomic, retain) UIImageView * line;
@end

@implementation QrCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   self.automaticallyAdjustsScrollViewInsets=NO;
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    _output = [[AVCaptureMetadataOutput alloc]init];
    
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    _session = [[AVCaptureSession alloc]init];
    
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    [_session addInput:self.input];
        
    [_session addOutput:self.output];
        
  

    
    // 条码类型 AVMetadataObjectTypeQRCode
    
    //_output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
    _output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
    
    // Preview
    
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
    
    _preview.videoGravity =AVLayerVideoGravityResizeAspectFill;
    
    _preview.frame =self.view.layer.bounds;
    
  
    [self.view.layer insertSublayer:_preview atIndex:100];
    

    
//    __weak typeof(self) weakSelf = self;
//    [[NSNotificationCenter defaultCenter]addObserverForName:AVCaptureInputPortFormatDescriptionDidChangeNotification
//                                                     object:nil
//                                                      queue:[NSOperationQueue mainQueue]
//                                                 usingBlock:^(NSNotification * _Nonnull note) {
//                                                     if (weakSelf){
//                                                      
//                                                       [_output  setRectOfInterest:CGRectMake((124)/kScreenHeight,((kScreenWidth-220)/2)/kScreenWidth,220/kScreenHeight,220/kScreenWidth)];
//                                                        
//                                                     }
//                                                 }];
    UIImage *tableIcon = [UIImage imageNamed:@"btn_back"];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithImage:tableIcon style:UIBarButtonItemStylePlain target:self action:@selector(changeToNavRootController:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithPatternImage:tableIcon];
   self.navigationItem.titleView=[AppUtils generateNavigationItemTitleViewWithTitle:@"扫描二维码"];
       [_session startRunning];
         [self creatBtn];
}
-(void)changeToNavRootController:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)creatBtn{
    
    
    
    _flshView=[[UIView alloc]initWithFrame:CGRectMake(30, 54+64, 48, 48)];
    _flshView.layer.cornerRadius=24;
    _flshView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_flshView];
    
    UIButton * flashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [flashBtn setImage:[UIImage imageNamed:@"light"] forState:UIControlStateNormal];
    flashBtn.frame = CGRectMake(30, 54+64, 48, 48);
    [flashBtn addTarget:self action:@selector(openFlash) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:flashBtn];
    
    UIButton * closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    closeBtn.frame = CGRectMake(485/2, 54+64, 48, 48);
    [closeBtn addTarget:self action:@selector(closeMa) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:closeBtn];
    
    
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(55, 848/2+64, self.view.frame.size.width-110, 28)];
    label.font = [UIFont systemFontOfSize:14];
    label.numberOfLines = 0;
    label.text = @"将二维码放到框内,即可自动扫描";
    label.textColor = [UIColor colorWithRed:255.0/255 green:255.0/255  blue:255.0/255  alpha:1];
    [self.view addSubview:label];
    
    UIImageView * kuangimageview = [[UIImageView alloc]initWithFrame:CGRectMake(41, 135+64, self.view.frame.size.width-82, self.view.frame.size.width-82)];
    kuangimageview.image = [UIImage imageNamed:@"kuang"];
    [self.view addSubview:kuangimageview];
    UIImageView * kuangimageview1 = [[UIImageView alloc]initWithFrame:CGRectMake(41, 135+64, self.view.frame.size.width-82, self.view.frame.size.width-82)];
    kuangimageview1.image = [UIImage imageNamed:@"guang"];
    [self.view addSubview:kuangimageview1];
    
    upOrdown = NO;
    num =0;
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 135+64, 320, 2)];
    _line.image = [UIImage imageNamed:@"line@2x.png"];
    [self.view addSubview:_line];
    
    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    
    
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSLog(@"___________________");
    [self.session stopRunning];
    [_preview removeFromSuperlayer];
    [timer setFireDate:[NSDate distantFuture]];
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
       
  [Qrcodem updateAddNumIsFinishById:obj.stringValue success:^(NetWorkBaseResponse *responseObject) {
      
      NSString *str;
      if(responseObject.code.intValue==1)
      {
          str=@"确认成功";
          
      }
      else str=responseObject.msg;
      UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:str  delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
      [alert show];

  } failure:^(NSError *error) {
      NSLog(@"%@",error.localizedDescription);
  }];
        
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}
//关闭二维码
-(void)closeMa{
    
    NSLog(@"关闭二维码");
    [timer setFireDate:[NSDate distantFuture]];
    [self.navigationController popViewControllerAnimated:YES];
   // exit(0);//完全退出程序(闪退画面)
    
}


//打开闪光灯
-(void)openFlash{
    NSLog(@"打开闪关灯");
    static BOOL a=YES;
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    if(a==YES){
        
        if ([device hasTorch]) {
            
            [device lockForConfiguration:nil];
            
            [device setTorchMode: AVCaptureTorchModeOn];
            _flshView.backgroundColor=[UIColor colorWithRed:123/255.0 green:103/255.0 blue:94/255.0 alpha:1];
            [device unlockForConfiguration];
            
        }
        a=NO;
        
    }else if(a==NO){
        if ([device hasTorch]) {
            
            [device lockForConfiguration:nil];
            
            [device setTorchMode: AVCaptureTorchModeOff];
            _flshView.backgroundColor=[UIColor clearColor];
            [device unlockForConfiguration];
            
            
        }
        a=YES;
    }
}


-(void)backAction
{
    
    [self dismissViewControllerAnimated:YES completion:^{
        [timer invalidate];
    }];
}
-(void)animation1
{
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake(50, 132+2*num+64, 220, 2);
        if (2*num == 240) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame = CGRectMake(50, 132+2*num+64, 220, 2);
        if (num == 0) {
            upOrdown = NO;
        }
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        
        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载 ，在WWDC视频也忽视这一点。
        
        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
        
    }
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
